package com.bcbim.api_web.space.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bcbim.authentication_interface.util.AuthUtil;
import com.bcbim.common.response.vo.ReturnMsg;
import com.bcbim.common.sys.Constant;
import com.bcbim.common.sys.ParamException;
import com.bcbim.common.sys.ReturnStatus;
import com.bcbim.common.util.GuidUtil;
import com.bcbim.common.util.HttpURLConnectionUtil;
import com.bcbim.common.util.ParamCheck;
import com.bcbim.model_server_interface.floor.service.FloorService;
import com.bcbim.operation_maintenance_interface.business_department.service.BusinessDepartmentService;
import com.bcbim.operation_maintenance_interface.business_department.vo.ListBusinessDepartmentTreeVO;
import com.bcbim.operation_maintenance_interface.department.dao.DepartmentDAO;
import com.bcbim.operation_maintenance_interface.department.dto.DepartmentDTO;
import com.bcbim.operation_maintenance_interface.department.service.DepartmentService;
import com.bcbim.operation_maintenance_interface.space.dao.SpaceDAO;
import com.bcbim.operation_maintenance_interface.space.dao.SpaceRecordDAO;
import com.bcbim.operation_maintenance_interface.space.dto.*;
import com.bcbim.operation_maintenance_interface.space.service.SpaceService;
import com.bcbim.operation_maintenance_interface.space.vo.*;
import com.bcbim.operation_maintenance_interface.space_category.service.SpaceCategoryService;
import com.bcbim.operation_maintenance_interface.space_category.vo.ListSpaceCategoryTreeVO;
import com.bcbim.operation_maintenance_interface.space_category.vo.SpaceCategoryVO;
import com.bcbim.operation_maintenance_interface.space_type.dao.SpaceTypeDAO;
import com.bcbim.operation_maintenance_interface.space_type.dto.SpaceTypeDTO;
import com.bcbim.operation_maintenance_interface.space_type.dto.SpaceTypeUnassignedDTO;
import com.bcbim.operation_maintenance_interface.space_type.service.SpaceTypeService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @version V 1.0.0
 * @Description：空controller
 * @Author: haomeijie
 * @Date: 2022/3/8 15:42
 **/
@RestController
@RequestMapping("/space")
public class SpaceController {
    @Reference(protocol = "dubbo", group = "space", version = "1.0.0")
    private SpaceService spaceServiceImpl;
    @Reference(protocol = "dubbo", group = "spaceCategory", version = "1.0.0")
    private SpaceCategoryService spaceCategoryServiceImpl;
    @Reference(protocol = "dubbo", group = "businessDepartment", version = "1.0.0")
    private BusinessDepartmentService businessDepartmentServiceImpl;
    @Reference(protocol = "dubbo", group = "floor", version = "1.0.0")
    private FloorService floorServiceImpl;
    @Reference(protocol = "dubbo", group = "spaceType", version = "1.0.0")
    private SpaceTypeService spaceTypeServiceImpl;
    @Reference(protocol = "dubbo", group = "department", version = "1.0.0")
    private DepartmentService departmentServiceImpl;
    @Value("${application.upload-path}")
    private String UPLOAD_PATH;

    /**
     * 空间列表查询
     *
     * @param spaceDTO
     * @return ReturnMsg
     * @Author: haomeijie
     * @Date: 2022/3/8 15:46
     */
    @RequestMapping("/listSpace")
    public ReturnMsg listSpace(SpaceDTO spaceDTO) {
        try {
            ParamCheck.idCheck(spaceDTO.getProjectId());
        } catch (ParamException e) {
            return ReturnMsg.consFail(ParamException.PARAMETER_ERROR);
        }
        //整理筛选条件
        if (StringUtils.isNotEmpty(spaceDTO.getSpaceTypeJson())) {
            List<SpaceTypeDTO> typeDTOList = JSONObject.parseArray(spaceDTO.getSpaceTypeJson(), SpaceTypeDTO.class);
            spaceDTO.setSpaceTypeIds(typeDTOList);
        }
        if (StringUtils.isNotEmpty(spaceDTO.getDepartmentJson())) {
            List<DepartmentDTO> departmentDTOList = JSONObject.parseArray(spaceDTO.getDepartmentJson(), DepartmentDTO.class);
            spaceDTO.setDepartmentIds(departmentDTOList);
        }
        //列表查询
        List<ListSpaceVO> list = spaceServiceImpl.listSpace(spaceDTO);
        //空间面积总数
        Double sumSpaceArea = 0.00;
        //额定人数总数
        Integer sumFixPeople = 0;
        //实际人数总数
        Integer sumActualPeople = 0;
        //空间数总数
        Integer sumSpaceCount = 0;
        //进行合计
        for (ListSpaceVO listSpaceVO : list) {
            sumSpaceArea += listSpaceVO.getSpaceArea();
            sumFixPeople += listSpaceVO.getFixPeopleNum();
            sumActualPeople += listSpaceVO.getActualPeopleNum();
            sumSpaceCount += listSpaceVO.getSpaceCount();
        }
        DecimalFormat df = new DecimalFormat("#.00");
        String str = df.format(sumSpaceArea);
        sumSpaceArea = Double.valueOf(str);
        //返回值整理
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", list);
        jsonObject.put("sumSpaceArea", sumSpaceArea);
        jsonObject.put("sumFixPeople", sumFixPeople);
        jsonObject.put("sumActualPeople", sumActualPeople);
        jsonObject.put("sumSpaceCount", sumSpaceCount);
        return ReturnMsg.consSuccess(jsonObject);
    }

    /**
     * 空间信息列表
     *
     * @param spaceInfoDTO
     * @return ReturnPageMsg
     * @Author: haomeijie
     * @Date: 2022/3/9 20:07
     */
    @RequestMapping("/listSpaceInfo")
    public ReturnMsg listSpaceInfo(SpaceInfoDTO spaceInfoDTO) {
        //参数校验
        try {
            ParamCheck.pageNumCheck(spaceInfoDTO.getPageNum(), spaceInfoDTO.getPageSize());
            ParamCheck.idCheck(spaceInfoDTO.getProjectId());
        } catch (ParamException e) {
            return ReturnMsg.consFail(ParamException.PARAMETER_ERROR);
        }
        //整理筛选条件
        if (StringUtils.isNotEmpty(spaceInfoDTO.getSpaceTypeJson())) {
            List<SpaceTypeDTO> typeDTOList = JSONObject.parseArray(spaceInfoDTO.getSpaceTypeJson(), SpaceTypeDTO.class);
            spaceInfoDTO.setSpaceTypeIds(typeDTOList);
        }
        if (StringUtils.isNotEmpty(spaceInfoDTO.getDepartmentJson())) {
            List<DepartmentDTO> departmentDTOList = JSONObject.parseArray(spaceInfoDTO.getDepartmentJson(), DepartmentDTO.class);
            spaceInfoDTO.setDepartmentIds(departmentDTOList);
        }
        //将排序json转成对象
        List<OrderDTO> orderDTO = JSONObject.parseArray(spaceInfoDTO.getJsonQuery(), OrderDTO.class);
        orderDTO.stream().forEach(order -> {
            if (order.getField().equals("spaceNum")) {
                order.setField("(" + order.getField() + "+ 0)");
            }
        });
        spaceInfoDTO.setOrderList(orderDTO);
        //调用服务
        List<ListSpaceInfoVO> list = new ArrayList<>();
        int total = spaceServiceImpl.listSpaceInfoCount(spaceInfoDTO);
        if (total > 0) {
            spaceInfoDTO.setStart((spaceInfoDTO.getPageNum() - 1) * spaceInfoDTO.getPageSize());
            list = spaceServiceImpl.listSpaceInfo(spaceInfoDTO);
        }
        //统计数据
        spaceInfoDTO.setStart(null);
        spaceInfoDTO.setPageSize(null);
        List<ListSpaceInfoVO> totalList = spaceServiceImpl.listSpaceInfo(spaceInfoDTO);
        double spaceArea = 0.00;
        int fixPeopleNum = 0;
        int actualPeopleNum = 0;
        for (ListSpaceInfoVO listSpaceInfoVO : totalList) {
            spaceArea += listSpaceInfoVO.getSpaceArea();
            if (ObjectUtils.isNotEmpty(listSpaceInfoVO.getFixPeopleNum())) {
                fixPeopleNum += listSpaceInfoVO.getFixPeopleNum();
            }
            if (ObjectUtils.isNotEmpty(listSpaceInfoVO.getActualPeopleNum())) {
                actualPeopleNum += listSpaceInfoVO.getActualPeopleNum();
            }
        }
        DecimalFormat df = new DecimalFormat("#.00");
        String str = df.format(spaceArea);
        spaceArea = Double.valueOf(str);
        Map<String, Object> map = new HashMap<>();
        map.put("list", list);
        map.put("areaSum", spaceArea);
        map.put("total", total);
        map.put("fixPeopleNum", fixPeopleNum);
        map.put("actualPeopleNum", actualPeopleNum);
        return ReturnMsg.consSuccess(map);

    }

    /**
     * 查看空间信息
     *
     * @param id
     * @return returnMsg
     * @Author: haomeijie
     * @Date: 2022/3/9 19:16
     */
    @RequestMapping("/getSpace")
    public ReturnMsg getSpace(String id) {
        //参数校验
        try {
            ParamCheck.idCheck(id);
        } catch (ParamException e) {
            return ReturnMsg.consFail(ParamException.PARAMETER_ERROR);
        }
        //调用服务
        SpaceVO spaceVO = spaceServiceImpl.getSpace(id);
        return ReturnMsg.consSuccess(spaceVO);
    }

    /**
     * 编辑空间信息
     *
     * @param spaceDAO
     * @return ReturnMsg
     * @Author: haomeijie
     * @Date: 2022/3/9 19:18
     */
    @RequestMapping("/updateSpace")
    public ReturnMsg updateSpace(SpaceDAO spaceDAO) {
        //参数校验
        if (StringUtils.isEmpty(spaceDAO.getSpaceTypeId())) {
            //类别未指派
            String categoryUnassignedId = spaceCategoryServiceImpl.getUnassignedId(Constant.UNASSIGNED, spaceDAO.getProjectId());
            String typeUnassignedId = null;
            //如果是未指派类别不生成未指派类型
            if (!spaceDAO.getSpaceCategoryId().equals(categoryUnassignedId)) {
                //获取类型未指派id
                SpaceTypeUnassignedDTO typeUnassignedDTO = new SpaceTypeUnassignedDTO();
                typeUnassignedDTO.setProjectId(spaceDAO.getProjectId());
                typeUnassignedDTO.setSpaceCategoryId(spaceDAO.getSpaceCategoryId());
                typeUnassignedDTO.setUnassignedName(Constant.UNASSIGNED);
                typeUnassignedId = spaceTypeServiceImpl.getUnassignedId(typeUnassignedDTO);
                if (StringUtils.isEmpty(typeUnassignedId)) {
                    //如果为空，生成类型未指派数据
                    SpaceTypeDAO spaceTypeDAO = new SpaceTypeDAO();
                    typeUnassignedId = GuidUtil.get();
                    spaceTypeDAO.setId(typeUnassignedId)
                            .setSpaceCategoryId(spaceDAO.getSpaceCategoryId())
                            .setProjectId(spaceDAO.getProjectId())
                            .setSpaceType(Constant.UNASSIGNED)
                            .setCreateBy(AuthUtil.getUserIdDecrypt())
                            .setCreateTime(LocalDateTime.now())
                            .setDel(Constant.NOT_DEL);
                    spaceTypeServiceImpl.insertSpaceType(spaceTypeDAO);
                }
            } else {
                //如果是类别未指派，则类型置null
                spaceDAO.setSpaceTypeId(null);
            }
            spaceDAO.setSpaceTypeId(typeUnassignedId);
        }
        if (StringUtils.isEmpty(spaceDAO.getDepartmentId())) {
            //查询未指派业务部id
            String businessUnassignedId = businessDepartmentServiceImpl.getUnassignedId(Constant.UNASSIGNED, spaceDAO.getProjectId());
            String departmentUnassignedId = null;
            if (!spaceDAO.getBusinessDepartmentId().equals(businessUnassignedId)) {
                //获取部门未指派id
                departmentUnassignedId = departmentServiceImpl.getUnassignedId(spaceDAO.getBusinessDepartmentId(), Constant.UNASSIGNED);
                if (StringUtils.isEmpty(departmentUnassignedId)) {
                    //如果为空，生成部门未指派数据
                    DepartmentDAO departmentDAO = new DepartmentDAO();
                    departmentUnassignedId = GuidUtil.get();
                    departmentDAO.setId(departmentUnassignedId);
                    departmentDAO.setProjectId(spaceDAO.getProjectId());
                    departmentDAO.setBusinessDepartmentId(spaceDAO.getBusinessDepartmentId());
                    departmentDAO.setDepartmentName(Constant.UNASSIGNED);
                    departmentDAO.setCreateBy(AuthUtil.getUserIdDecrypt());
                    departmentDAO.setCreateTime(LocalDateTime.now());
                    departmentDAO.setDel(Constant.NOT_DEL);
                    departmentServiceImpl.insertDepartment(departmentDAO);
                }
            } else {
                //如果是业务部是未指派，则部门置null
                spaceDAO.setDepartmentId(null);
            }
            spaceDAO.setDepartmentId(departmentUnassignedId);
        }
        try {
            ParamCheck.idCheck(spaceDAO.getId());
            ParamCheck.stringCanBeEmpty(spaceDAO.getAllocationMethod(), 1);
            ParamCheck.idCanBeEmpty(spaceDAO.getBusinessDepartmentId());
            ParamCheck.idCanBeEmpty(spaceDAO.getDepartmentId());
            ParamCheck.idCanBeEmpty(spaceDAO.getSpaceCategoryId());
            ParamCheck.idCanBeEmpty(spaceDAO.getSpaceTypeId());
        } catch (ParamException e) {
            return ReturnMsg.consFail(ParamException.PARAMETER_ERROR);
        }
        //整理参数
        spaceDAO.setUpdateBy(AuthUtil.getUserIdDecrypt())
                .setUpdateTime(LocalDateTime.now());

        //保存变更记录
        SpaceRecordDAO spaceRecordDAO = new SpaceRecordDAO();
        spaceDAO.setSpaceId(spaceDAO.getId());
        BeanUtils.copyProperties(spaceDAO, spaceRecordDAO);
        spaceRecordDAO.setId(GuidUtil.get());
        spaceServiceImpl.saveSpaceRecord(spaceRecordDAO);
        //调用服务
        int i = spaceServiceImpl.updateSpace(spaceDAO);
        return i == 1 ? ReturnMsg.consSuccess(Constant.SAVE_SUCCESS) : ReturnMsg.consFail(Constant.SAVE_FAIL);
    }

    /**
     * 批量指派空间类型部门
     *
     * @param updateSpaceDTO
     * @return ReturnMsg
     * @Author: haomeijie
     * @Date: 2022/3/17 17:37
     */
    @RequestMapping("/batchUpdateSpace")
    public ReturnMsg batchUpdateSpace(UpdateSpaceDTO updateSpaceDTO) {
        //参数校验
        try {
            //校验空间id
            for (String id : updateSpaceDTO.getSpaceIds()) {
                ParamCheck.idCheck(id);
            }
            ParamCheck.idCheck(updateSpaceDTO.getProjectId());
            //参数校验
            if (StringUtils.isEmpty(updateSpaceDTO.getSpaceTypeId())) {
                //类别未指派
                String categoryUnassignedId = spaceCategoryServiceImpl.getUnassignedId(Constant.UNASSIGNED, updateSpaceDTO.getProjectId());
                String typeUnassignedId = null;
                //如果是未指派类别不生成未指派类型
                if (!updateSpaceDTO.getSpaceCategoryId().equals(categoryUnassignedId)) {
                    //获取类型未指派id
                    //获取类型未指派id
                    SpaceTypeUnassignedDTO typeUnassignedDTO = new SpaceTypeUnassignedDTO();
                    typeUnassignedDTO.setProjectId(updateSpaceDTO.getProjectId());
                    typeUnassignedDTO.setSpaceCategoryId(updateSpaceDTO.getSpaceCategoryId());
                    typeUnassignedDTO.setUnassignedName(Constant.UNASSIGNED);
                    typeUnassignedId = spaceTypeServiceImpl.getUnassignedId(typeUnassignedDTO);
                    if (StringUtils.isEmpty(typeUnassignedId)) {
                        //如果为空，生成类型未指派数据
                        SpaceTypeDAO spaceTypeDAO = new SpaceTypeDAO();
                        typeUnassignedId = GuidUtil.get();
                        spaceTypeDAO.setId(typeUnassignedId)
                                .setProjectId(updateSpaceDTO.getProjectId())
                                .setSpaceCategoryId(updateSpaceDTO.getSpaceCategoryId())
                                .setSpaceType(Constant.UNASSIGNED)
                                .setCreateBy(AuthUtil.getUserIdDecrypt())
                                .setCreateTime(LocalDateTime.now())
                                .setDel(Constant.NOT_DEL);
                        spaceTypeServiceImpl.insertSpaceType(spaceTypeDAO);
                    }
                }
                updateSpaceDTO.setSpaceTypeId(typeUnassignedId);
            }
            if (StringUtils.isEmpty(updateSpaceDTO.getDepartmentId())) {
                //查询未指派业务部id
                String businessUnassignedId = businessDepartmentServiceImpl.getUnassignedId(Constant.UNASSIGNED, updateSpaceDTO.getProjectId());
                String departmentUnassignedId = null;
                if (!updateSpaceDTO.getBusinessDepartmentId().equals(businessUnassignedId)) {
                    //获取部门未指派id
                    departmentUnassignedId = departmentServiceImpl.getUnassignedId(updateSpaceDTO.getBusinessDepartmentId(), Constant.UNASSIGNED);
                    if (StringUtils.isEmpty(departmentUnassignedId)) {
                        //如果为空，生成部门未指派数据
                        DepartmentDAO departmentDAO = new DepartmentDAO();
                        departmentUnassignedId = GuidUtil.get();
                        departmentDAO.setId(departmentUnassignedId);
                        departmentDAO.setProjectId(updateSpaceDTO.getProjectId());
                        departmentDAO.setBusinessDepartmentId(updateSpaceDTO.getBusinessDepartmentId());
                        departmentDAO.setDepartmentName(Constant.UNASSIGNED);
                        departmentDAO.setCreateBy(AuthUtil.getUserIdDecrypt());
                        departmentDAO.setCreateTime(LocalDateTime.now());
                        departmentDAO.setDel(Constant.NOT_DEL);
                        departmentServiceImpl.insertDepartment(departmentDAO);
                    }
                }
                updateSpaceDTO.setDepartmentId(departmentUnassignedId);
            }
            ParamCheck.idCanBeEmpty(updateSpaceDTO.getBusinessDepartmentId());
            ParamCheck.idCanBeEmpty(updateSpaceDTO.getDepartmentId());
            ParamCheck.idCanBeEmpty(updateSpaceDTO.getSpaceCategoryId());
            ParamCheck.idCanBeEmpty(updateSpaceDTO.getSpaceTypeId());
        } catch (ParamException e) {
            e.printStackTrace();
        }
        //整理参数
        int i = 0;
        for (String id : updateSpaceDTO.getSpaceIds()) {
            SpaceDAO spaceDAO = new SpaceDAO();
            //参数同步
            BeanUtils.copyProperties(updateSpaceDTO, spaceDAO);
            spaceDAO.setId(id)
                    .setUpdateBy(AuthUtil.getUserIdDecrypt())
                    .setUpdateTime(LocalDateTime.now());
            //调用服务
            i += spaceServiceImpl.updateSpace(spaceDAO);
            //保存变更记录
            SpaceRecordDAO spaceRecordDAO = new SpaceRecordDAO();
            spaceDAO.setSpaceId(spaceDAO.getId());
            BeanUtils.copyProperties(spaceDAO, spaceRecordDAO);
            spaceRecordDAO.setId(GuidUtil.get());
            spaceServiceImpl.saveSpaceRecord(spaceRecordDAO);
        }
        return i > 0 ? ReturnMsg.consSuccess(Constant.SAVE_SUCCESS) : ReturnMsg.consFail(Constant.SAVE_FAIL);
    }

    /**
     * 类别-类型中列表
     *
     * @param spaceDTO
     * @return ReturnMsg
     * @Author: haomeijie
     * @Date: 2022/3/10 15:40
     */
    @RequestMapping("/listSpaceByCategory")
    public ReturnMsg listSpaceByCategory(SpaceDTO spaceDTO) {
        //参数校验
        try {
            ParamCheck.idCheck(spaceDTO.getProjectId());
        } catch (ParamException e) {
            return ReturnMsg.consFail(ParamException.PARAMETER_ERROR);
        }
        //整理筛选条件
        if (StringUtils.isNotEmpty(spaceDTO.getSpaceTypeJson())) {
            List<SpaceTypeDTO> typeDTOList = JSONObject.parseArray(spaceDTO.getSpaceTypeJson(), SpaceTypeDTO.class);
            spaceDTO.setSpaceTypeIds(typeDTOList);
            List<String> categoryIds = new ArrayList<>();
            List<String> typeIds = new ArrayList<>();
            typeDTOList.stream().forEach(spaceTypeDTO -> {
                String spaceCategoryId = spaceTypeDTO.getSpaceCategoryId();
                String spaceTypeId = spaceTypeDTO.getSpaceTypeId();
                if (StringUtils.isNotEmpty(spaceCategoryId)) {
                    categoryIds.add(spaceCategoryId);
                }
                if (StringUtils.isNotEmpty(spaceTypeId)) {
                    typeIds.add(spaceTypeId);
                }
            });
            spaceDTO.setCategoryIds(categoryIds);
            spaceDTO.setTypeIds(typeIds);
        }
        if (StringUtils.isNotEmpty(spaceDTO.getDepartmentJson())) {
            List<DepartmentDTO> departmentDTOList = JSONObject.parseArray(spaceDTO.getDepartmentJson(), DepartmentDTO.class);
            spaceDTO.setDepartmentIds(departmentDTOList);
        }
        //列表
        List<ListSpaceCategoryTreeVO> list = spaceCategoryServiceImpl.listCategoryType(spaceDTO);
//        //有筛选条件按照筛选条件筛选
//        if (ObjectUtils.isNotEmpty(spaceDTO.getFloorIds()) || StringUtils.isNotEmpty(spaceDTO.getSpaceTypeJson())
//                || StringUtils.isNotEmpty(spaceDTO.getDepartmentJson()) || StringUtils.isNotEmpty(spaceDTO.getSpaceNumber())
//                || StringUtils.isNotEmpty(spaceDTO.getSpaceName()) || spaceDTO.getIsBlank()) {
//            list = spaceCategoryServiceImpl.listCategoryBySpace(spaceDTO);
//        } else {
//            //没有，查询所有
//            list = spaceCategoryServiceImpl.listSpaceByCategory(spaceDTO);
//        }
        int sum = 0;
        for (ListSpaceCategoryTreeVO treeVO : list) {
            sum += treeVO.getSpaceCount();
        }
        Map<String, Object> map = new HashMap<>();
        map.put("list", list);
        map.put("sum", sum);
        return ReturnMsg.consSuccess(map);
    }

//    /**
//     * 根据材质信息查询空间详情信息
//     *
//     * @param materialDTO
//     * @return ReturnMsg
//     * @Author: haomeijie
//     * @Date: 2022/3/10 18:05
//     */
//    @RequestMapping("/getSpaceByMaterial")
//    public ReturnMsg getSpaceByMaterial(MaterialDTO materialDTO) {
//        //参数校验
//        List<MaterialDTO> list = new ArrayList<>();
//        list.add(materialDTO);
//        List<ListSpaceAssignVO> listSpaceAssignVO = spaceServiceImpl.getSpaceByMaterial(list);
//        SpaceAssignVO spaceAssignVO = new SpaceAssignVO();
//        BeanUtils.copyProperties(listSpaceAssignVO.get(0), spaceAssignVO);
//        return ReturnMsg.consSuccess(spaceAssignVO);
//    }

    /**
     * 修改空间类型和部门
     *
     * @param spaceAssignDTO
     * @return ReturnMsg
     * @Author: haomeijie
     * @Date: 2022/3/11 17:20
     */
    @RequestMapping("updateSpaceByIds")
    public ReturnMsg updateSpaceByIds(SpaceAssignDTO spaceAssignDTO) {
        //参数校验
        try {
            for (String id : spaceAssignDTO.getSpaceIds()) {
                ParamCheck.idCheck(id);
            }
            ParamCheck.idCheck(spaceAssignDTO.getProjectId());
            //参数判空
            //参数校验
            if (StringUtils.isNotEmpty(spaceAssignDTO.getSpaceCategoryId()) && StringUtils.isEmpty(spaceAssignDTO.getSpaceTypeId())) {
                //类别未指派
                String categoryUnassignedId = spaceCategoryServiceImpl.getUnassignedId(Constant.UNASSIGNED, spaceAssignDTO.getProjectId());
                String typeUnassignedId = null;
                //如果是未指派类别不生成未指派类型
                if (!spaceAssignDTO.getSpaceCategoryId().equals(categoryUnassignedId)) {
                    //获取类型未指派id
                    SpaceTypeUnassignedDTO typeUnassignedDTO = new SpaceTypeUnassignedDTO();
                    typeUnassignedDTO.setProjectId(spaceAssignDTO.getProjectId());
                    typeUnassignedDTO.setSpaceCategoryId(spaceAssignDTO.getSpaceCategoryId());
                    typeUnassignedDTO.setUnassignedName(Constant.UNASSIGNED);
                    typeUnassignedId = spaceTypeServiceImpl.getUnassignedId(typeUnassignedDTO);
                    if (StringUtils.isEmpty(typeUnassignedId)) {
                        //如果为空，生成类型未指派数据
                        SpaceTypeDAO spaceTypeDAO = new SpaceTypeDAO();
                        typeUnassignedId = GuidUtil.get();
                        spaceTypeDAO.setId(typeUnassignedId)
                                .setProjectId(spaceAssignDTO.getProjectId())
                                .setSpaceCategoryId(spaceAssignDTO.getSpaceCategoryId())
                                .setSpaceType(Constant.UNASSIGNED)
                                .setCreateBy(AuthUtil.getUserIdDecrypt())
                                .setCreateTime(LocalDateTime.now())
                                .setDel(Constant.NOT_DEL);
                        spaceTypeServiceImpl.insertSpaceType(spaceTypeDAO);
                    }
                }
                spaceAssignDTO.setSpaceTypeId(typeUnassignedId);
            }
            if (StringUtils.isNotEmpty(spaceAssignDTO.getBusinessDepartmentId()) && StringUtils.isEmpty(spaceAssignDTO.getDepartmentId())) {
                //查询未指派业务部id
                String businessUnassignedId = businessDepartmentServiceImpl.getUnassignedId(Constant.UNASSIGNED, spaceAssignDTO.getProjectId());
                String departmentUnassignedId = null;
                if (!spaceAssignDTO.getBusinessDepartmentId().equals(businessUnassignedId)) {
                    //获取部门未指派id
                    departmentUnassignedId = departmentServiceImpl.getUnassignedId(spaceAssignDTO.getBusinessDepartmentId(), Constant.UNASSIGNED);
                    if (StringUtils.isEmpty(departmentUnassignedId)) {
                        //如果为空，生成部门未指派数据
                        DepartmentDAO departmentDAO = new DepartmentDAO();
                        departmentUnassignedId = GuidUtil.get();
                        departmentDAO.setId(departmentUnassignedId);
                        departmentDAO.setProjectId(spaceAssignDTO.getProjectId());
                        departmentDAO.setBusinessDepartmentId(spaceAssignDTO.getBusinessDepartmentId());
                        departmentDAO.setDepartmentName(Constant.UNASSIGNED);
                        departmentDAO.setCreateBy(AuthUtil.getUserIdDecrypt());
                        departmentDAO.setCreateTime(LocalDateTime.now());
                        departmentDAO.setDel(Constant.NOT_DEL);
                        departmentServiceImpl.insertDepartment(departmentDAO);
                    }
                }
                spaceAssignDTO.setDepartmentId(departmentUnassignedId);
            }
            //参数判空
            if (StringUtils.isEmpty(spaceAssignDTO.getSpaceCategoryId())) {
                spaceAssignDTO.setSpaceCategoryId(null);
            }
            if (StringUtils.isEmpty(spaceAssignDTO.getSpaceTypeId())) {
                spaceAssignDTO.setSpaceTypeId(null);
            }
            if (StringUtils.isEmpty(spaceAssignDTO.getBusinessDepartmentId())) {
                spaceAssignDTO.setBusinessDepartmentId(null);
            }
            if (StringUtils.isEmpty(spaceAssignDTO.getDepartmentId())) {
                spaceAssignDTO.setDepartmentId(null);
            }
            ParamCheck.idCanBeEmpty(spaceAssignDTO.getSpaceCategoryId());
            ParamCheck.idCanBeEmpty(spaceAssignDTO.getSpaceTypeId());
            ParamCheck.idCanBeEmpty(spaceAssignDTO.getBusinessDepartmentId());
            ParamCheck.idCanBeEmpty(spaceAssignDTO.getDepartmentId());
        } catch (ParamException e) {
            return ReturnMsg.consFail(ParamException.PARAMETER_ERROR);
        }
        //整理参数
        int i = 0;
        for (String id : spaceAssignDTO.getSpaceIds()) {
            SpaceDAO spaceDAO = new SpaceDAO();
            spaceDAO.setId(id)
                    .setProjectId(spaceAssignDTO.getProjectId())
                    .setSpaceCategoryId(spaceAssignDTO.getSpaceCategoryId())
                    .setSpaceTypeId(spaceAssignDTO.getSpaceTypeId())
                    .setBusinessDepartmentId(spaceAssignDTO.getBusinessDepartmentId())
                    .setDepartmentId(spaceAssignDTO.getDepartmentId())
                    .setUpdateBy(AuthUtil.getUserIdDecrypt())
                    .setUpdateTime(LocalDateTime.now());
            i = spaceServiceImpl.updateSpace(spaceDAO);

            //保存变更记录
            SpaceRecordDAO spaceRecordDAO = new SpaceRecordDAO();
            spaceDAO.setSpaceId(spaceDAO.getId());
            BeanUtils.copyProperties(spaceDAO, spaceRecordDAO);
            spaceRecordDAO.setId(GuidUtil.get());
            spaceServiceImpl.saveSpaceRecord(spaceRecordDAO);
        }
        return i > 0 ? ReturnMsg.consSuccess(Constant.SAVE_SUCCESS) : ReturnMsg.consFail(Constant.SAVE_FAIL);
    }

    /**
     * 业务部门-部门查询空间列表
     *
     * @param spaceDTO
     * @return ReturnMsg
     * @Author: haomeijie
     * @Date: 2022/3/15 15:46
     */
    @RequestMapping("/listSpaceByDepartment")
    public ReturnMsg listSpaceByDepartment(SpaceDTO spaceDTO) {
        //参数校验
        try {
            ParamCheck.idCheck(spaceDTO.getProjectId());
        } catch (ParamException e) {
            return ReturnMsg.consFail(ParamException.PARAMETER_ERROR);
        }
        //整理筛选条件
        if (StringUtils.isNotEmpty(spaceDTO.getSpaceTypeJson())) {
            List<SpaceTypeDTO> typeDTOList = JSONObject.parseArray(spaceDTO.getSpaceTypeJson(), SpaceTypeDTO.class);
            spaceDTO.setSpaceTypeIds(typeDTOList);
        }
        if (StringUtils.isNotEmpty(spaceDTO.getDepartmentJson())) {
            List<DepartmentDTO> departmentDTOList = JSONObject.parseArray(spaceDTO.getDepartmentJson(), DepartmentDTO.class);
            spaceDTO.setDepartmentIds(departmentDTOList);
            List<String> businessId = new ArrayList<>();
            List<String> departmentId = new ArrayList<>();
            departmentDTOList.stream().forEach(departmentDTO -> {
                String businessIds = departmentDTO.getBusinessDepartmentId();
                String departmentIds = departmentDTO.getDepartmentId();
                if (StringUtils.isNotEmpty(businessIds)) {
                    businessId.add(businessIds);
                }
                if (StringUtils.isNotEmpty(departmentIds)) {
                    departmentId.add(departmentIds);
                }
            });
            spaceDTO.setBusinessId(businessId);
            spaceDTO.setDepartmentId(departmentId);
        }
        //列表
        List<ListBusinessDepartmentTreeVO> list = businessDepartmentServiceImpl.listDepartment(spaceDTO);
        //有筛选条件按照筛选条件筛选
//        if (ObjectUtils.isNotEmpty(spaceDTO.getFloorIds()) || StringUtils.isNotEmpty(spaceDTO.getSpaceTypeJson())
//                || StringUtils.isNotEmpty(spaceDTO.getDepartmentJson()) || StringUtils.isNotEmpty(spaceDTO.getSpaceNumber())
//                || StringUtils.isNotEmpty(spaceDTO.getSpaceName()) || spaceDTO.getIsBlank()) {
//            list = businessDepartmentServiceImpl.listDepartmentBySpace(spaceDTO);
//        } else {
//            //没有筛选条件查询所有
//            list = businessDepartmentServiceImpl.listSpaceByDepartment(spaceDTO);
//        }
        int sum = 0;
        for (ListBusinessDepartmentTreeVO treeVO : list) {
            sum += treeVO.getSpaceCount();
        }
        Map<String, Object> map = new HashMap<>();
        map.put("list", list);
        map.put("sum", sum);
        return ReturnMsg.consSuccess(map);
    }

    /**
     * 模型操作中空间信息列表
     *
     * @param serverIds 模型id
     * @return
     * @Author: haomeijie
     * @Date: 2022/3/16 10:14
     */
    @RequestMapping("/listSpaceByMaterial")
    public ReturnMsg listSpaceByMaterial(String[] serverIds) {
        Map<String, Object> map = new HashMap<>();
        //参数校验
        try {
            for (String id : serverIds) {
                ParamCheck.idCheck(id);
            }
        } catch (ParamException e) {
            return ReturnMsg.consFail(ParamException.PARAMETER_ERROR);
        }
        List<ListSpaceAssignVO> listSpaceAssign = spaceServiceImpl.getSpaceByMaterial(serverIds);
        Double spaceAreaSum = 0.00;
        Integer fixPeopleNumSum = 0;
        for (ListSpaceAssignVO listSpaceAssignVO : listSpaceAssign) {
            spaceAreaSum += listSpaceAssignVO.getSpaceArea();
            fixPeopleNumSum += listSpaceAssignVO.getFixPeopleNum();
        }
        DecimalFormat df = new DecimalFormat("#.00");
        String str = df.format(spaceAreaSum);
        spaceAreaSum = Double.valueOf(str);
        map.put("list", listSpaceAssign);
        map.put("spaceAreaSum", spaceAreaSum);
        map.put("fixPeopleNumSum", fixPeopleNumSum);
        return ReturnMsg.consSuccess(map);
    }

    /**
     * 根据选中空间统计空间面积
     *
     * @param serverIds
     * @return ReturnMsg
     * @Author: haomeijie
     * @Date: 2022/3/19 11:02
     */
    @RequestMapping("/getSpaceAreaSum")
    public ReturnMsg getSpaceAreaSum(String[] serverIds) {
        //参数校验
        try {
            for (String id : serverIds) {
                ParamCheck.idCheck(id);
            }
        } catch (ParamException e) {
            return ReturnMsg.consFail(ParamException.PARAMETER_ERROR);
        }
        //查询条件
        Double spaceAreaSum = spaceServiceImpl.getSpaceAreaSum(serverIds);
        return ReturnMsg.consSuccess(spaceAreaSum);
    }

    /**
     * 导出空间信息列表
     *
     * @param spaceInfoDTO
     * @return ReturnMsg
     * @Author: haomeijie
     * @Date: 2022/3/18 14:05
     */
    @RequestMapping("/exportSpace")
    public ReturnMsg exportSpace(SpaceInfoDTO spaceInfoDTO) {
        //参数校验
        try {
            ParamCheck.idCheck(spaceInfoDTO.getProjectId());
        } catch (ParamException e) {
            return ReturnMsg.consFail(ParamException.PARAMETER_ERROR);
        }
        //整理筛选条件
        if (StringUtils.isNotEmpty(spaceInfoDTO.getSpaceTypeJson())) {
            List<SpaceTypeDTO> typeDTOList = JSONObject.parseArray(spaceInfoDTO.getSpaceTypeJson(), SpaceTypeDTO.class);
            spaceInfoDTO.setSpaceTypeIds(typeDTOList);
        }
        if (StringUtils.isNotEmpty(spaceInfoDTO.getDepartmentJson())) {
            List<DepartmentDTO> departmentDTOList = JSONObject.parseArray(spaceInfoDTO.getDepartmentJson(), DepartmentDTO.class);
            spaceInfoDTO.setDepartmentIds(departmentDTOList);
        }
        String path = spaceServiceImpl.exportSpace(spaceInfoDTO, AuthUtil.getUserIdDecrypt(), UPLOAD_PATH);
        if (StringUtils.isNotEmpty(path)) {
            return ReturnMsg.newInstance().setData(path).setStatus(ReturnStatus.SUCCESS.getCode());
        }
        return ReturnMsg.consFail("导出失败！");
    }

    /**
     * 导出空间类型列表
     *
     * @param spaceDTO
     * @return ReturnMsg
     * @Author: haomeijie
     * @Date: 2022/3/18 15:04
     */
    @RequestMapping("/exportCategory")
    public ReturnMsg exportCategory(SpaceDTO spaceDTO) {
        try {
            ParamCheck.idCheck(spaceDTO.getProjectId());
        } catch (ParamException e) {
            return ReturnMsg.consFail(ParamException.PARAMETER_ERROR);
        }
        //整理筛选条件
        if (StringUtils.isNotEmpty(spaceDTO.getSpaceTypeJson())) {
            List<SpaceTypeDTO> typeDTOList = JSONObject.parseArray(spaceDTO.getSpaceTypeJson(), SpaceTypeDTO.class);
            spaceDTO.setSpaceTypeIds(typeDTOList);
            List<String> categoryIds = new ArrayList<>();
            List<String> typeIds = new ArrayList<>();
            typeDTOList.stream().forEach(spaceTypeDTO -> {
                String spaceCategoryId = spaceTypeDTO.getSpaceCategoryId();
                String spaceTypeId = spaceTypeDTO.getSpaceTypeId();
                if (StringUtils.isNotEmpty(spaceCategoryId)) {
                    categoryIds.add(spaceCategoryId);
                }
                if (StringUtils.isNotEmpty(spaceTypeId)) {
                    typeIds.add(spaceTypeId);
                }
            });
            spaceDTO.setCategoryIds(categoryIds);
            spaceDTO.setTypeIds(typeIds);
        }
        if (StringUtils.isNotEmpty(spaceDTO.getDepartmentJson())) {
            List<DepartmentDTO> departmentDTOList = JSONObject.parseArray(spaceDTO.getDepartmentJson(), DepartmentDTO.class);
            spaceDTO.setDepartmentIds(departmentDTOList);
        }
        //列表
        List<ListSpaceCategoryTreeVO> list = spaceCategoryServiceImpl.listCategoryType(spaceDTO);
        String path = spaceServiceImpl.exportCategory(list, AuthUtil.getUserIdDecrypt(), spaceDTO.getProjectId(), UPLOAD_PATH);
        if (StringUtils.isNotEmpty(path)) {
            return ReturnMsg.newInstance().setData(path).setStatus(ReturnStatus.SUCCESS.getCode());
        }
        return ReturnMsg.consFail("导出失败！");
    }

    /**
     * 空间部门导出
     *
     * @param spaceDTO
     * @return ReturnMsg
     * @Author: haomeijie
     * @Date: 2022/3/18 15:44
     */
    @RequestMapping("/exportDepartment")
    public ReturnMsg exportDepartment(SpaceDTO spaceDTO) {
        try {
            ParamCheck.idCheck(spaceDTO.getProjectId());
        } catch (ParamException e) {
            return ReturnMsg.consFail(ParamException.PARAMETER_ERROR);
        }
        //整理筛选条件
        if (StringUtils.isNotEmpty(spaceDTO.getSpaceTypeJson())) {
            List<SpaceTypeDTO> typeDTOList = JSONObject.parseArray(spaceDTO.getSpaceTypeJson(), SpaceTypeDTO.class);
            spaceDTO.setSpaceTypeIds(typeDTOList);
        }
        if (StringUtils.isNotEmpty(spaceDTO.getDepartmentJson())) {
            List<DepartmentDTO> departmentDTOList = JSONObject.parseArray(spaceDTO.getDepartmentJson(), DepartmentDTO.class);
            spaceDTO.setDepartmentIds(departmentDTOList);
            List<String> businessId = new ArrayList<>();
            List<String> departmentId = new ArrayList<>();
            departmentDTOList.stream().forEach(departmentDTO -> {
                String businessIds = departmentDTO.getBusinessDepartmentId();
                String departmentIds = departmentDTO.getDepartmentId();
                if (StringUtils.isNotEmpty(businessIds)) {
                    businessId.add(businessIds);
                }
                if (StringUtils.isNotEmpty(departmentIds)) {
                    departmentId.add(departmentIds);
                }
            });
            spaceDTO.setBusinessId(businessId);
            spaceDTO.setDepartmentId(departmentId);
        }
        //列表
        List<ListBusinessDepartmentTreeVO> list = businessDepartmentServiceImpl.listDepartment(spaceDTO);
        String path = spaceServiceImpl.exportDepartment(list, AuthUtil.getUserIdDecrypt(), spaceDTO.getProjectId(), UPLOAD_PATH);
        if (StringUtils.isNotEmpty(path)) {
            return ReturnMsg.newInstance().setData(path).setStatus(ReturnStatus.SUCCESS.getCode());
        }
        return ReturnMsg.consFail("导出失败！");
    }

    /**
     * 根据颜色显示查询空间颜色
     *
     * @param spaceColorTypeDTO
     * @return ReturnMsg
     * @Author: haomeijie
     * @Date: 2022/3/19 15:18
     */
    @RequestMapping("/selectSpaceByColor")
    public ReturnMsg selectSpaceByColor(SpaceColorTypeDTO spaceColorTypeDTO) {
        //参数校验
        try {
            ParamCheck.stringCanBeEmpty(spaceColorTypeDTO.getType(), 1);
            ParamCheck.idCheck(spaceColorTypeDTO.getFloorId());
            ParamCheck.idCheck(spaceColorTypeDTO.getProjectId());
        } catch (ParamException e) {
            return ReturnMsg.consFail(ParamException.PARAMETER_ERROR);
        }
        List<SpaceColorVO> list = spaceServiceImpl.selectSpaceByColor(spaceColorTypeDTO);
        return ReturnMsg.consSuccess(list);
    }

    /**
     * 根据标签显示查询标签
     *
     * @param spaceColorTypeDTO
     * @return ReturnMsg
     * @Author: haomeijie
     * @Date: 2022/3/22 10:05
     */
    @RequestMapping("/selectSpaceByLabel")
    public ReturnMsg selectSpaceByLabel(SpaceColorTypeDTO spaceColorTypeDTO) {
        //参数校验
        try {
            ParamCheck.stringCanBeEmpty(spaceColorTypeDTO.getType(), 1);
            ParamCheck.idCheck(spaceColorTypeDTO.getFloorId());
            ParamCheck.idCheck(spaceColorTypeDTO.getProjectId());
        } catch (ParamException e) {
            return ReturnMsg.consFail(ParamException.PARAMETER_ERROR);
        }
        List<SpaceLabelVO> list = spaceServiceImpl.selectSpaceByLabel(spaceColorTypeDTO);
        return ReturnMsg.consSuccess(list);
    }

    /**
     * 获取坐标中点
     *
     * @param modelServerId
     * @return ReturnMsg
     * @Author: haomeijie
     * @Date: 2022/3/31 10:52
     */
    @RequestMapping("/getCenterByFloorId")
    public ReturnMsg getCenterByFloorId(String modelServerId) {
        try {
            ParamCheck.idCheck(modelServerId);
        } catch (ParamException e) {
            return ReturnMsg.consFail(ParamException.PARAMETER_ERROR);
        }
        //查询空间
        String paramComponent = "arrFileId=" + modelServerId;
        String resultComponent = HttpURLConnectionUtil.doPost("/component/getComponentCenter", paramComponent);
        JSONObject jsonObject = JSONObject.parseObject(resultComponent);
        JSONArray data = jsonObject.getJSONArray("data");
        return ReturnMsg.consSuccess(data);
    }

    /**
     * 变更记录
     *
     * @param spaceId
     * @author xuehao
     * @createDate 2022/4/28 14:07
     * @retuen ReturnMsg
     */
    @PostMapping("/listSpaceRecord")
    public ReturnMsg listSpaceRecord(String spaceId) {
        try {
            ParamCheck.idCheck(spaceId);
        } catch (ParamException e) {
            return ReturnMsg.consFail(ParamException.PARAMETER_ERROR);
        }
        List<SpaceRecordListVO> list = spaceServiceImpl.listSpaceRecord(spaceId);
        return ReturnMsg.consSuccess(list);
    }

    /**
     * 判断空间是否存在人员
     *
     * @param checkSpaceDTO
     * @return spaceCategoryId
     * @Author: haomeijie
     * @Date: 2022/5/30 16:00
     */
    @RequestMapping("/checkSpaceExitStaff")
    public ReturnMsg checkSpaceExitStaff(CheckSpaceDTO checkSpaceDTO) {
        try {
            ParamCheck.idCheck(checkSpaceDTO.getSpaceCategoryId());
            for (String id : checkSpaceDTO.getSpaceIds()) {
                ParamCheck.idCheck(id);
            }
        } catch (ParamException e) {
            return ReturnMsg.consFail(ParamException.PARAMETER_ERROR);
        }
        //校验类别是否可占用
        SpaceCategoryVO spaceCategory = spaceCategoryServiceImpl.getSpaceCategory(checkSpaceDTO.getSpaceCategoryId());
        boolean b = false;
        if (StringUtils.isEmpty(spaceCategory.getOccupy()) || spaceCategory.getOccupy().equals(Constant.NOT_OCCUPY)) {
            b = spaceServiceImpl.checkSpaceExitStaff(checkSpaceDTO.getSpaceIds());
        }
        return ReturnMsg.consSuccess(b);
    }

}
